<?php
namespace app\api\controller;

use app\common\exception\BusinessException;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use think\Response;
use think\response\Json;

class QrCode extends Base
{
    /**
     * 显示Url
     * @return Response
     * @throws BusinessException
     */
    public function show(): Response
    {
        // 请求参数
        $url = $this->request->param('url', '');
        if (!$url)
        {
            throw new BusinessException('二维码地址不得为空');
        }

        // 生成二维码
        $qrCode = new \Endroid\QrCode\QrCode();
        $qrCode->setSize(300);
        $qrCode->setMargin(10);
        $qrCode->setLabel('保存到相册-扫一扫支付', 12, null, LabelAlignment::CENTER);
        $qrCode->setEncoding('UTF-8');
        $qrCode->setText($url);
        $qrCode->setRoundBlockSize(true);
        $qrCode->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::HIGH));
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);

        // 返回
        return Response::create($qrCode->writeString())->code(200)->header(['Content-Type' => 'image/png']);
    }
}